<template>
	<view class="add-invoice-header" :style="{ paddingTop: `${getSystemInfo.navBarHeight}px` }">
		<navBar :title="pageTitle"></navBar>
		<view :style="{ height: `calc(100vh - ${getSystemInfo.navBarHeight}px)` }">
			<view class="aih-body">
				<u--form ref="formRef" label-width="80px" error-type="toast" :model="formData"
					:label-style="{ fontSize: '28rpx', color: '#646464' }">
					<view class="form-block">
						<!-- 发票类型 -->
						<u-form-item label="发票类型">
							<view class="tag-radio">
								<view class="tr-item" v-for="(item, index) in types" :key="index">
									<u-tag plain :text="item.name" :name="item.value"
										:border-color="!item.checked && '#646464'" :color="!item.checked && '#646464'"
										@click="isAdd && onCheckType(item.value)">
									</u-tag>
								</view>
							</view>
						</u-form-item>

						<!-- 抬头类型 -->
						<u-form-item label="抬头类型">
							<view class="tag-radio">
								<view class="tr-item" v-for="(item, index) in headerTypes" :key="index">
									<u-tag plain :text="item.name" :name="item.value"
										:border-color="!item.checked && '#646464'" :color="!item.checked && '#646464'"
										@click="isAdd && onCheckHeaderType(item.value)">
									</u-tag>
								</view>
							</view>
						</u-form-item>
						<!-- 抬头名称 -->
						<u-form-item label="抬头名称" prop="titleName" v-if="formData.invoiceType == 1" required>
							<u--input v-model="formData.titleName" border="bottom" placeholder="必填"></u--input>
						</u-form-item>
						<view class="form-block-bg form-item-pic" v-if="isVAT" style="margin: 20rpx 0 0;">
							<!-- 一般纳税人证明 -->
							<u-form-item label="一般纳税人证明" prop="taxpayerCertificateImg" required labelWidth="220">
								<view class="pic-content">
									<!-- <image
							v-if="!formData.nashui"
							class="upload-pic"
							src="https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/mine/invoice_pic.png"
							mode=""
						></image>
						<image
							v-else
							class="upload-pic"
							src="formData.nashui"
							mode=""
						></image> -->
									<uploadImg :width="80" :height="70" :previewUrl="[formData.taxpayerCertificateImg]"
										@deleteImg="formData.taxpayerCertificateImg = ''"
										@handleImg="(url) => formData.taxpayerCertificateImg = url" />
									<text style="color:#CF1A1B;margin-right:20rpx;" @click="onPreview(1)">照片示例</text>
								</view>
							</u-form-item>
							<!-- 单位营业执照 -->
							<u-form-item label="单位营业执照" prop="businessLicenseImg" required labelWidth="220">
								<view class="pic-content">
									<uploadImg :width="80" :height="70" :previewUrl="[formData.businessLicenseImg]"
										@deleteImg="formData.businessLicenseImg = ''"
										@handleImg="(url) => formData.businessLicenseImg = url" />
									<text style="color:#CF1A1B;margin-right:20rpx;" @click="onPreview(2)">照片示例</text>
								</view>
							</u-form-item>
							<!-- 物流公司委托司机购买轮胎的委托书 -->
							<u-form-item label="物流公司委托司机购买轮胎的委托书" prop="powerAttorneyImg" required labelWidth="300">
								<view class="pic-content">
									<uploadImg :width="80" :height="70" :previewUrl="[formData.powerAttorneyImg]"
										@deleteImg="formData.powerAttorneyImg = ''"
										@handleImg="(url) => formData.powerAttorneyImg = url" />
									<text style="color:#CF1A1B;margin-right:20rpx;" @click="onPreview(3)">照片示例</text>
								</view>
							</u-form-item>
						</view>

						<view class="form-block-bg" v-if="isVAT" style="margin: 20rpx 0 0;">
							<view class="title">法人身份证</view>
							<uploadSFZ @handleURL="handleURL" @handleDelURl="handleDelURl"
								:bossBackImgUrl="formData.bossBackImg" :bossJustImgUrl="formData.bossJustImg" />
						</view>

						<template v-if="isCompanyHeader">
							<!-- 抬头名称 -->
							<u-form-item label="抬头名称" prop="titleName" v-if="formData.invoiceType == 0" required>
								<u--input v-model="formData.titleName" border="bottom" placeholder="必填"></u--input>
							</u-form-item>

							<!-- 单位税号 -->
							<u-form-item label="单位税号" prop="taxNo" required>
								<u--input v-model="formData.taxNo" border="bottom" placeholder="必填"></u--input>
							</u-form-item>

							<!-- 注册地址 -->
							<u-form-item label="注册地址" prop="address" :required="formData.invoiceType == 1">
								<u--input v-model="formData.address" border="bottom"
									:placeholder="isVAT ? '必填' : '选填'"></u--input>
							</u-form-item>

							<!-- 注册电话 -->
							<u-form-item label="注册电话" prop="telephone" :required="formData.invoiceType == 1">
								<u--input v-model="formData.telephone" border="bottom"
									:placeholder="isVAT ? '必填' : '选填'"></u--input>
							</u-form-item>

							<!-- 开户银行 -->
							<u-form-item label="开户银行" prop="bankName" :required="formData.invoiceType == 1">
								<u--input v-model="formData.bankName" border="bottom"
									:placeholder="isVAT ? '必填' : '选填'"></u--input>
							</u-form-item>

							<!-- 银行账号 -->
							<u-form-item label="银行账号" prop="bankNo" :required="formData.invoiceType == 1">
								<u--input v-model="formData.bankNo" border="bottom"
									:placeholder="isVAT ? '必填' : '选填'"></u--input>
							</u-form-item>
						</template>

						<template v-else>
							<!-- 抬头名称 -->
							<u-form-item label="抬头名称" prop="titleName" required>
								<u--input v-model="formData.titleName" border="bottom" placeholder="必填"></u--input>
							</u-form-item>
						</template>
						<!-- 默认抬头 -->
						<u-form-item label="默认抬头">
							<view class="default-header-switch">
								<text>开发票会优先选择该抬头</text>
								<u-switch v-model="formData.defaultFlag" active-value="Y" inactive-value="N"
									:size="40"></u-switch>
							</view>
						</u-form-item>

						<template v-if="isVAT">
							<!-- 增值税填写收票信息 -->
							<view>
								<view class="title">收票地址</view>
								<!-- 收票人 -->
								<u-form-item label="收票人" prop="receiptPerson" required>
									<u--input v-model="formData.receiptPerson" border="bottom"
										placeholder="请输入收票人姓名"></u--input>
								</u-form-item>

								<!-- 联系电话 -->
								<u-form-item label="联系电话" prop="receiptTel" required>
									<u--input v-model="formData.receiptTel" border="bottom"
										placeholder="请输入联系电话"></u--input>
								</u-form-item>

								<!-- 所在地区 -->
								<u-form-item label="所在地区" required>
									<picker mode="region" @change="onChangeArea">
										<view class="select-input">
											<u--input :value="areaText" placeholder="请选择所在地区" border="bottom"
												readonly></u--input>
											<view class="icon-arrow">
												<u-icon name="arrow-right"></u-icon>
											</view>
										</view>
									</picker>
								</u-form-item>

								<!-- 详细地址 -->
								<u-form-item label="详细地址" prop="receiptAddressDetail" required>
									<u--input v-model="formData.receiptAddressDetail" border="bottom"
										placeholder="请输入详细地址"></u--input>
								</u-form-item>
							</view>
						</template>

					</view>
				</u--form>
				<!-- 是否同意协议 -->
				<view class="protocol" v-if="isVAT">
					<u-checkbox-group v-model="protocol">
						<u-checkbox name="agree" size="18px" icon-size="14px" label-size="14px" shape="circle"
							label="我已阅读并同意">
						</u-checkbox>
					</u-checkbox-group>
					<text class="name" @click="visibleProtocol = true">《增值税专用发票抬头确认书》</text>
				</view>
			</view>

			<!-- 协议内容 -->
			<u-popup :show="visibleProtocol" :round="10" :safe-area-inset-bottom="false" closeable
				class="protocol-popup" @close="visibleProtocol = false">
				<view class="protocol-content">
					<view class="pc-header">
						<text>增值税专用发票抬头确认书</text>
					</view>
					<view class="pc-body">
						<text>根据国家税法及发票管理相关规定，任何单位和个人不得要求他人为自己开具与实际经营业务情况不符的增值税专用发票(包括并不限于(1)在没有货物采购或者没有接受应税劳务的情况下要求他人为自己开具增值税专用发票;(2)虽有货物采购或者接受应税劳务但要求他人为自己开具数量或金额与实际情况不符的增值税专用发票]，
							否则属于“虚开增值税专用发票”。</text>
						<text>我已充分了解上述各项相关国家税法和发票管理规定，并确认仅就我司实际购买商品或服务索取发票。如我司未按国家相关规定申请开具或使用增值税专用发票，由我司自行承担相应法律后果。</text>
					</view>
					<view class="pc-footer">
						<u-button type="primary" text="确定" @click="onConfirmProtocol"></u-button>
					</view>
				</view>
			</u-popup>

			<view class="aih-button">
				<u-button v-if="!isAdd" type="primary" text="删除" plain @click="visibleDelete = true"></u-button>
				<u-button type="primary" text="保存" :disabled="isVAT && !isAgree" @click="onSave"></u-button>
			</view>

			<!-- 弹窗：删除 -->
			<u-modal :show="visibleDelete" title="确定要删除该抬头信息吗？" :showCancelButton="true" cancelText="取消"
				confirmText="确定" confirmColor="#CF1A1B" @confirm="onDelete" @cancel="visibleDelete = false">
			</u-modal>
		</view>

		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		mapState,
		mapGetters,
		mapMutations
	} from 'vuex'
	import navBar from '@/components/navBar.vue'
	import uploadImg from '@/components/uploadImg.vue'
	import uploadSFZ from '@/components/uploadSFZ.vue'
	const defaultFormData = {
		id: undefined, // 仅编辑
		invoiceType: 0, // 发票类型；0-电子普通发票，1-增值税专用发票
		titleType: 0, // 抬头类型；0-单位，1-个人/非企业单位
		titleName: '', // 抬头名称
		taxNo: '', // 税号
		address: '', // 地址
		telephone: '', // 电话,
		bankName: '', // 开户银行
		bankNo: '', // 银行账号
		receiptPerson: '', // 收票人
		receiptTel: '', // 收票人联系电话
		receiptProvince: '', // 收票-省
		receiptCity: '', // 收票-市
		receiptCounty: '', // 收票-区
		receiptAddressDetail: '', // 收票人详细地址
		defaultFlag: 'N', // 是否默认
		businessLicenseImg: '', //营业执照照片
		bossBackImg: '', //身份证照片反面
		bossJustImg: '', //身份证照片正面
		taxpayerCertificateImg: '', //纳税人证明照片
		powerAttorneyImg: '' //委托书照片
	}

	export default {
		components: {
			navBar,
			uploadImg,
			uploadSFZ
		},
		data() {
			return {
				// 发票类型
				types: [{
						name: '电子普通发票',
						value: 0,
						checked: true
					},
					{
						name: '增值税专用发票',
						value: 1,
						checked: false
					},
				],
				// 抬头类型
				headerTypes: [{
						name: '单位',
						value: 0,
						checked: true
					},
					{
						name: '个人/非企业单位',
						value: 1,
						checked: false
					},
				],

				// 同意协议
				protocol: [],

				// 协议内容弹窗
				visibleProtocol: false,

				// 删除弹窗
				visibleDelete: false,

				// 提交数据
				formData: {
					...defaultFormData
				},

				// 校验规则
				rules: {
					businessLicenseImg: [{
						required: true,
						message: '请上传营业执照照片'
					}],
					bossBackImg: [{
						required: true,
						message: '请上传身份证照片反面'
					}],
					bossJustImg: [{
						required: true,
						message: '请上传身份证照片正面'
					}],
					taxpayerCertificateImg: [{
						required: true,
						message: '请上传纳税人证明照片'
					}],
					powerAttorneyImg: [{
						required: true,
						message: '请上传委托书照片'
					}],
					titleName: [{
						required: true,
						message: '请输入抬头名称'
					}],
					taxNo: [{
						required: true,
						message: '请输入单位税号'
					}],
					address: [{
						required: true,
						message: '请输入注册地址'
					}],
					telephone: [{
							required: true,
							message: '请输入注册电话'
						},
						{
							// pattern: /0\d{2,3}-\d{7,8}/g,
							pattern: /^\d(\d|-)+\d$/g,
							message: '注册电话格式不正确'
						}
					],
					bankName: [{
						required: true,
						message: '请输入开户银行'
					}],
					bankNo: [{
						required: true,
						message: '请输入银行账号'
					}],
					receiptTel: [{
						validator: (rule, value, callback) => {
							return !!value ? uni.$u.test.mobile(value) : true
						},
						message: '手机号码不正确',
						trigger: ['change', 'blur'],
					}]
				},

				// 页面标题
				pageTitle: '',
			}
		},
		computed: {
			...mapGetters('global', ['getSystemInfo']),
			...mapState('user', ['userInfo']),

			// 是否增值税发票
			isVAT() {
				return this.types[1].checked
			},
			// 是否公司抬头
			isCompanyHeader() {
				return this.headerTypes[0].checked
			},
			// 是否有个人类型抬头选项
			hasPersonType() {
				return this.headerTypes.some(item => item.name === '个人/非企业单位')
			},
			// 是否同意协议
			isAgree() {
				return this.protocol[0] === 'agree'
			},
			// 区域文本显示
			areaText() {
				const {
					receiptProvince,
					receiptCity,
					receiptCounty
				} = this.formData
				if (receiptProvince) {
					return `${receiptProvince} ${receiptCity} ${receiptCounty}`
				}
				return ''
			},
			// 是否新增
			isAdd() {
				return !this.formData.id
			}
		},
		methods: {
			handleDelURl(type) {
				if (type === 'zheng') {
					this.formData.bossJustImg = ''
				} else {
					this.formData.bossBackImg = ''
				}
			},
			handleURL({
				type,
				url
			}) {
				if (type === 'zheng') {
					this.formData.bossJustImg = url
				} else {
					this.formData.bossBackImg = url
				}
			},
			// 保存
			async onSave() {
				// 格式校验
				await this.$refs.formRef.validate()
				try {
					// 请求参数
					const params = {
						...this.formData
					}
					if (this.isAdd) {
						params.userId = this.userInfo.id
					}
					// loading
					uni.showLoading({
						title: '网络请求中',
						mask: true
					})
					// 请求
					const url = this.isAdd ? '/order-center/invoice/title/save' : '/order-center/invoice/title/update'
					await this.$request({
						url,
						data: params
					})
					// 请求成功
					uni.hideLoading()
					uni.showToast({
						title: '请求成功',
						icon: 'success',
						mask: true
					})
					setTimeout(() => {
						uni.navigateBack({
							success: () => {
								const eventChannel = this.getOpenerEventChannel()
								eventChannel.emit('update')
							}
						})
					}, 1500)
				} catch (err) {
					uni.hideLoading()
					this.$refs.uToast.show({
						message: err.respMsg || '请求失败',
						position: 'top'
					})
				}
			},

			// 删除
			async onDelete() {
				try {
					uni.showLoading({
						mask: true
					})
					await this.$request({
						url: '/order-center/invoice/title/delete',
						data: {
							ids: [this.formData.id]
						},
					})
					uni.hideLoading()
					uni.showToast({
						title: '请求成功',
						icon: 'success',
						mask: true
					})
					this.visibleDelete = false
					setTimeout(() => {
						uni.navigateBack({
							success: () => {
								const eventChannel = this.getOpenerEventChannel()
								eventChannel.emit('update')
							}
						})
					}, 1500)
				} catch (err) {
					uni.hideLoading()
					this.$refs.uToast.show({
						message: err.respMsg || '请求失败',
						position: 'top'
					})
				}
			},

			// 获取发票抬头信息（编辑时）
			async getHeaderDetails() {
				uni.showLoading({
					title: '加载中...'
				})
				try {
					const {
						datas
					} = await this.$request({
						url: `/order-center/invoice/title/desc/${this.formData.id}`,
						method: 'GET'
					})
					delete datas.createdTime
					this.checkType(datas.invoiceType)
					this.checkHeaderType(datas.titleType)
					this.$set(this, 'formData', datas)
				} catch (err) {
					//
				}
				uni.hideLoading()
			},

			// 所在地区改变
			onChangeArea(e) {
				const value = e.detail.value || []
				this.formData.receiptProvince = value[0]
				this.formData.receiptCity = value[1]
				this.formData.receiptCounty = value[2]
			},

			// 选择发票类型
			checkType(value) {
				this.types.forEach(item => {
					item.checked = item.value === value
					if (item.value === value) {
						this.formData.invoiceType = item.value
					}
				})
				if (value === this.types[0].value && !this.hasPersonType) {
					// 选择电子普通发票，恢复个人抬头选项
					this.headerTypes.push({
						name: '个人/非企业单位',
						value: 1,
						checked: false
					})
					// 设置电子普通发票的表单校验规则
					this.setCommonInvoiceRule()
				} else if (value === this.types[1].value) {
					// 选择增值税发票，只显示公司抬头选项
					this.headerTypes = [{
						name: '单位',
						value: 0,
						checked: true
					}]
					this.formData.titleType = 0
					// 设置增值税发票表单校验规则
					this.setVatInvoiceRule()
				}
			},
			onCheckType(value) {
				this.resetForm({
					whiteList: ['orderIds']
				})
				this.checkType(value)
			},

			// 选择抬头类型
			checkHeaderType(value) {
				this.headerTypes.forEach(item => {
					item.checked = item.value === value
					if (item.value === value) {
						this.formData.titleType = item.value
					}
				})
			},
			onCheckHeaderType(value) {
				this.resetForm({
					whiteList: ['orderIds', 'invoiceType']
				})
				this.checkHeaderType(value)
			},

			// 重置表单
			resetForm(options = {}) {
				const whiteList = options.whiteList || [] // 不需要重置的字段
				Object.keys(this.formData).forEach(key => {
					if (!whiteList.includes(key)) {
						this.formData[key] = defaultFormData[key]
					}
				})
				this.$refs.formRef.clearValidate()
			},

			// 设置电子普通发票表单校验规则
			setCommonInvoiceRule() {
				const {
					titleName,
					taxNo,
					telephone
				} = this.rules
				if (this.formData.titleType == 1) {
					this.$refs.formRef.setRules({
						titleName,
						telephone: [telephone[1]]
					})
				} else {
					this.$refs.formRef.setRules({
						titleName,
						taxNo,
						telephone: [telephone[1]]
					})
				}
			},

			// 设置增值税发票校验规则
			setVatInvoiceRule() {
				this.$refs.formRef.setRules(this.rules)
			},

			// 确认协议
			onConfirmProtocol() {
				this.protocol = ['agree']
				this.visibleProtocol = false
			},
			//图片预览
			onPreview(val) {
				var urlList = []
				if (val == 1) {
					urlList = [
						'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/mine/nsrzm_pic1.png',
						'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/mine/nsrzm_pic2.png',
						'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/mine/nsrzm_pic3.png'
					]
				}
				if (val == 2) {
					urlList = [
						'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/mine/yyzz_pic.png']
				}
				if (val == 3) {
					urlList = ['https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/mine/wts_pic.png']
				}
				uni.previewImage({
					indicator: "number",
					loop: true,
					urls: urlList
				})
			},
		},
		onReady() {
			this.setCommonInvoiceRule()
		},
		onLoad() {
			const eventChannel = this.getOpenerEventChannel()
			// 新增
			eventChannel.on('add', () => {
				this.pageTitle = '添加抬头'
			})

			// 修改
			eventChannel.on('edit', (id) => {
				// uni.setNavigationBarTitle({ title: '编辑抬头信息' })
				this.pageTitle = '编辑抬头'
				this.formData.id = id
				this.protocol.push('agree')
				this.getHeaderDetails()
			})
		}
	}
</script>

<style scoped lang="scss">
	.add-invoice-header {
		padding: 20rpx 0 0;

		/deep/ .u-form-item__body {
			padding: 4px 0 !important;
		}

		.aih-body {
			height: calc(100% - 32rpx - 40px - env(safe-area-inset-bottom));
			// padding: 0 32rpx;
			font-size: 28rpx;
			background-color: #fff;
			overflow-y: auto;
		}

		.form-block {
			background-color: #fff;
			padding: 32rpx;

			.title {
				line-height: 1.5;
				margin-bottom: 10rpx;
			}

			.form-block-bg {
				background-color: #fff;
				padding: 32rpx 0;

				.title {
					line-height: 1.5;
					margin-bottom: 10rpx;
				}
			}

			.form-item-pic {
				/deep/ .u-form-item {
					padding: 15rpx 0;
					border-bottom: 0.5px solid #dadbde;
				}

				.pic-content {
					display: flex;
					flex-direction: row-reverse;
					align-items: center;

					/deep/ .u-upload__button {
						margin: 0;
					}

					/deep/ .u-upload__wrap__preview {
						margin: 0;
					}

					.upload-pic {
						width: 80rpx;
						height: 70rpx;
					}
				}
			}
		}

		.select-input {
			display: flex;
			flex-direction: row;
			justify-content: space-between;

			.icon-arrow {
				border-bottom: 0.5px solid #dadbde;
				display: flex;
				align-items: center;
			}
		}

		.default-header-switch {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			padding: 20rpx 0;
			border-bottom: 0.5px solid #dadbde;
		}

		.tag-radio {
			display: flex;
			flex-direction: row;
			gap: 24rpx;
			padding: 15rpx 0;
			border-bottom: 0.5px solid #dadbde;

			.tr-item {
				width: calc((100% - 24rpx) / 2);
			}

			/deep/ .u-tag {
				justify-content: center;
			}
		}

		.aih-button {
			padding: 32rpx 32rpx env(safe-area-inset-bottom);
			background-color: #fff;
			display: flex;
			flex-direction: row;
			gap: 10rpx;
		}

		.protocol {
			display: flex;
			padding: 32rpx;

			.name {
				color: $uni-primary;
			}
		}

		.protocol-content {
			.pc-header {
				height: 104rpx;
				border-bottom: 1px solid rgba(0, 0, 0, 0.08);
				text-align: center;
				font-size: 32rpx;
				line-height: 104rpx;
			}

			.pc-body {
				padding: 34rpx 60rpx 0;
				font-size: 28rpx;
				color: rgba(0, 0, 0, 0.65);
				display: flex;
				flex-direction: column;
				gap: 40rpx;
				text-indent: 56rpx;
			}

			.pc-footer {
				padding: 32rpx;
				padding-bottom: env(safe-area-inset-bottom);
			}
		}

		/deep/ .u-popup__content__close {
			top: 16px !important;

			.uicon-close {
				font-size: 18px !important;
				line-height: 18px !important;
			}
		}
	}
</style>